//
//  CommentCommonCell.m
//  IfengNews
//
//  Created by tianhy on 12-12-26.
//
//

#import "CommentCommonCell.h"
#import "CLGloble.h"
#import "Define.h"
#import "CTCommentTable.h"
#import "DetailUtil.h"
#import "PlanningTopicCoreTextLabel.h"
#import "CalculatHeightForReplayCell.h"
#import "BlockUI.h"
#import "UIImageView+WebCache.h"
#import "UIView+Utils.h"
#import "SgrGCD.h"

@interface CommentCommonCell()

@property(nonatomic, strong) UIView *line;

@end

@implementation CommentCommonCell
@synthesize indexPath,dataDic,delegate,isSupported,isSupportClick;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.isSupportClick = YES;
    }
    return self;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor{
    [super setBackgroundColor:backgroundColor];
}

#pragma mark -
#pragma mark Construct Cell Views
- (void)setUpSubViews
{
    if([self.comeFrom isEqualToString:@"doc"])
        self.contentView.backgroundColor = RGB(0xf7, 0xf7, 0xf7);
    else
        self.contentView.backgroundColor = RGB(0xf7, 0xf7, 0xf7);
    
    [self performSelector:@selector(clearSubViews)];
    [self performSelector:@selector(addbackgroundView)];
    [self performSelector:@selector(initIconView)];
    [self performSelector:@selector(initZoneLabel)];
    [self performSelector:@selector(initSupportView)];
    [self performSelector:@selector(initCommentContentsLabel)];
    [self performSelector:@selector(addSeperatorLineView)];
//    if (!self.isSupportClick) {
//        [self performSelector:@selector(addSufaceView)];
//    }
    if([self.comeFrom isEqualToString:@"topic"])
        self.backgroundColor = RGB(0xf7, 0xf7, 0xf7);
    else if([self.comeFrom isEqualToString:@"doc"]){
        if(self.indexPath.row == 0)
            [self addTopLine];
        self.backgroundColor = [UIColor whiteColor];
    }
    else{
        self.backgroundColor = [UIColor whiteColor];
    }
}

- (void)clearSubViews
{
    [[self.contentView subviews] enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [(UIView *)obj removeFromSuperview];
    }];
}

- (void)addTopLine
{
    UIView *lineView = [UIView new];
    lineView.backgroundColor = RGB(0xd7, 0xd7, 0xd7);
    lineView.frame = CGRectMake(53,0.5, 254, 0.5);
    [self.contentView addSubview:lineView];
}


- (void)addbackgroundView
{
    IfengLabel *backgroundView = [[IfengLabel alloc] init];
    backgroundView.comeFrom = self.comeFrom;
    backgroundView.frame = CGRectMake(0, 0, 320, [CalculatHeightForReplayCell calculationCommonCommentHeightWithData:dataDic]);
    backgroundView.tag = 10;
    backgroundView.level = 1;
    backgroundView.delegate = self;
    backgroundView.dataDic = self.dataDic;
    backgroundView.index = 0;
    backgroundView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:backgroundView];
}

- (void)initIconView
{
    IfengLabel *backgroundView = (IfengLabel *)[self.contentView viewWithTag:10];
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.backgroundColor = RGB(0xf7, 0xf7, 0xf7);
    iconImageView.userInteractionEnabled = YES;
    if([self.comeFrom isEqualToString:@"doc"])
        iconImageView.frame = CGRectMake(leftmarginOfIcon, 0,iconSize.width,iconSize.height);
//    else if([self.comeFrom isEqualToString:@"topic"])
//        iconImageView.frame = CGRectMake(leftmarginOfIcon, 0, iconSize.width, iconSize.height);
    else
        iconImageView.frame = CGRectMake(leftmarginOfIcon, 0, iconSize.width,iconSize.height);
    iconImageView.layer.masksToBounds = YES;
    iconImageView.layer.cornerRadius = cornerRadiusOfIcon;
    [backgroundView addSubview:iconImageView];
    
    NSString *iconUrl = [self.dataDic sgrGetStringForKey:@"userFace"];
    if(![iconUrl isEqualToString:defaultUserIcon])
    {
//        [iconImageView reset2DefaultWithUrl:iconUrl];
//        [iconImageView setUrl4Image:iconUrl];
        [iconImageView sd_setImageWithURL:[NSURL URLWithString:iconUrl] placeholderImage:[UIImage imageNamed:@"comment_user_icon.png"]];
    }
    else
    {
        iconImageView.image = [UIImage imageNamed:@"comment_user_icon.png"];
    }
    
   
    
    
    NSString *ext2 = [dataDic sgrGetStringForKey:@"ext2"];
    NSString *guid = nil;
//    if(_isStrNotNull(ext2)){
//        NSDictionary *dic = [ext2 JSONValue];
//        guid = [dic sgrGetStringForKey:@"guid"];
//    }
//    if(_isStrNULL(guid))
//    {
//        UIView *coverView = [UIView new];
//        coverView.userInteractionEnabled = YES;
//        coverView.frame = iconImageView.bounds;
//        coverView.layer.masksToBounds = YES;
//        coverView.layer.cornerRadius = 12.0;
//        coverView.alpha = 0.45;
//        coverView.backgroundColor = ICurrentTheme.commentStyle.headCoverViewColor;
//        [iconImageView addSubview:coverView];
//    }
    
    UIButton *userHeadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    userHeadBtn.frame = CGRectMake(iconImageView.frame.origin.x-10, iconImageView.frame.origin.y, iconImageView.frame.size.width+20, iconImageView.frame.size.height+10);
    userHeadBtn.backgroundColor = [UIColor clearColor];
    [userHeadBtn addTarget:self action:@selector(nameTapResponse:) forControlEvents:UIControlEventTouchUpInside];
    [backgroundView addSubview:userHeadBtn];
    
   // if([[self.dataDic sgrGetStringForKey:@"profile"] hasPrefix:@"groupId=1"]){
    
    
    NSArray *arr1=[[self.dataDic sgrGetStringForKey:@"profile"] componentsSeparatedByString:@"&"];
  
    int icIndex=-1;
    for(NSString *str in arr1){
        if([str hasPrefix:@"groupId="]){
            icIndex=[[str stringByReplacingOccurrencesOfString:@"groupId=" withString:@""] intValue]-2;
            break;
        }
    }
    if(icIndex >=0){
        CGRect frame=[iconImageView convertRect:CGRectMake(iconImageView.width-9, iconImageView.height-9, 12, 12)
                                         toView:backgroundView];
        UIImageView *chan=[[UIImageView alloc] initWithFrame:frame];
        chan.image=[UIImage imageNamed:[[CLGloble sharedInstance].levelIcons sgrGetStringForIndex:icIndex]];
        [backgroundView addSubview:chan];
    }
}

- (NSString *)getNickName
{
    NSString *userName = nil;
    NSString *guid = nil;
    NSString *ext2 = [dataDic sgrGetStringForKey:@"ext2"];
//    if(_isStrNotNull(ext2)){
//        NSDictionary *dic = [ext2 JSONValue];
//        guid = [dic sgrGetStringForKey:@"guid"];
//        userName = [dic sgrGetStringForKey:@"nickname"];
//    }
    return userName;
}

- (void)initZoneLabel   //表示用户地域的Label
{
    IfengLabel *backgroundView = (IfengLabel *)[self.contentView viewWithTag:10];
   // NSString *ext2 = [dataDic sgrGetStringForKey:@"ext2"];
//    NSString *name = [Globle shareInstance].userEntity.userName;
    NSString *userName = nil;
    NSString *ipFromStr = [dataDic sgrGetStringForKey:@"ip_from"];
   // NSString *locationStr = (ipFromStr&&([ipFromStr length] > 6))?[ipFromStr substringToIndex:6]:ipFromStr;
    NSString *locationStr=ipFromStr;
    NSString *zoneStr = nil;
    
    
   // NSString *guid = nil;
//    if(_isStrNotNull(ext2)){
//        NSDictionary *dic = [ext2 JSONValue];
//        guid = [dic sgrGetStringForKey:@"guid"];
//        userName = [dic sgrGetStringForKey:@"nickname"];
//    }
    userName = [dataDic sgrGetStringForKey:@"uname"];
    if(_isStrNotNull(locationStr))
        userName=[NSString stringWithFormat:@"%@ • ",userName];
        
   
    
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.font = [UIFont systemFontOfSize:13];
    nameLabel.userInteractionEnabled = YES;
    nameLabel.backgroundColor = [UIColor clearColor];
//    if(_isStrNotNull(guid)){ //表示是登陆用户，可以点击
//        nameLabel.textColor = ICurrentTheme.commentStyle.commentNameTextColor;
//    }
//    else{
        nameLabel.textColor = RGB(0x5b, 0x85, 0x9e);
 //   }

//    if(userName.length > 8)
//    {
//        userName = [userName substringToIndex:8];
//    }
    nameLabel.text = userName;
    CGSize nameSize = [userName sizeWithFont:nameLabel.font
                           constrainedToSize:CGSizeMake(1000, zoneHeight)
                               lineBreakMode:NSLineBreakByWordWrapping];
    
    nameLabel.frame = CGRectMake(leftMarginOfComment, intervalFromTop, nameSize.width, zoneHeight);
    nameLabel.backgroundColor = [UIColor clearColor];
    [backgroundView addSubview:nameLabel];
    
//    UIButton *nameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    nameBtn.frame = CGRectMake(nameLabel.frame.origin.x, nameLabel.frame.origin.y-10, nameLabel.frame.size.width, nameLabel.frame.size.height+20);
//    nameBtn.backgroundColor = [UIColor clearColor];
//    [nameBtn addTarget:self action:@selector(nameTapResponse:) forControlEvents:UIControlEventTouchUpInside];
//    [backgroundView addSubview:nameBtn];
//    
    UILabel *zoneLabel = [[UILabel alloc] init];
    zoneLabel.tag = 1001;
    zoneLabel.numberOfLines = 1;
    zoneLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    zoneLabel.frame = CGRectMake(nameLabel.right,intervalFromTop,GlobleWidth-50.f,zoneHeight);
    zoneLabel.text = _isStrNULL(locationStr)?@"":locationStr;
    zoneLabel.font = [UIFont systemFontOfSize:12];
    zoneLabel.textColor = RGB(0x56, 0x56, 0x5e);
    zoneLabel.backgroundColor = [UIColor clearColor];
    [backgroundView addSubview:zoneLabel];
}

- (void)initSupportView
{
    IfengLabel *backgroundView = (IfengLabel *)[self.contentView viewWithTag:10];
    
    UIView *supportView = [[UIView alloc] init];
    supportView.tag = 10001;
    supportView.backgroundColor = [UIColor clearColor];
    supportView.frame = CGRectMake(backgroundView.width-rightMargin-70, intervalFromTop, 70, 12);
    [backgroundView addSubview:supportView];
  
    
    UIImageView *supportImgview = [[UIImageView alloc] init];
    supportImgview.backgroundColor = [UIColor clearColor];
    supportImgview.tag = 10002;
    if(!isSupported)
        supportImgview.image = [UIImage imageNamed:@"comment_replay_support.png"];
    else
        supportImgview.image = [UIImage imageNamed:@"comment_replay_supported.png"];
    [supportView addSubview:supportImgview];
    
    UILabel *supportCountNumLabel = [[UILabel alloc] init];
    supportCountNumLabel.tag = 10003;
    supportCountNumLabel.textAlignment = NSTextAlignmentRight;
    supportCountNumLabel.backgroundColor = [UIColor clearColor];
    supportCountNumLabel.textColor =  RGB(0x86, 0x86, 0x86);
    supportCountNumLabel.font = [UIFont fontWithName:@"Avenir-Oblique" size:11.];
    
    NSString *supportStr = [self.dataDic sgrFGetStringForKey:@"uptimes"];
    if(isSupported)
    {
        int supportCount = [supportStr intValue];
        supportCount++;
        supportStr = [NSString stringWithFormat:@"%d",supportCount];
    }
    
    
    if(!supportStr || [supportStr length] == 0 || [supportStr rangeOfString:@"null"].length > 0)
        supportStr = @"0";
    if([supportStr isEqualToString:@"0"])
        supportStr = @"";
    supportCountNumLabel.text = supportStr;
    
    CGSize supportStrSize = [supportStr sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(50, 12)];
    supportCountNumLabel.frame=CGRectMake(supportView.width-supportStrSize.width, 0, supportStrSize.width, 12);
    supportImgview.frame = CGRectMake(CGRectGetWidth(supportView.frame)-supportImgview.width-10, 0, 16, 16);
    supportCountNumLabel.frame = CGRectMake(CGRectGetWidth(supportView.frame)-supportCountNumLabel.width-supportImgview.frame.size.width, 5, supportCountNumLabel.width, 11);
    [supportView addSubview:supportCountNumLabel];
    
    UIButton *supportButton=[UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame=supportView.frame;
    frame.size.height+=20;
    frame.origin.y-=10.f;
    frame.origin.x+=20.f;
    supportButton.frame=frame;
    [backgroundView addSubview:supportButton];
    __weak typeof(self) me=self;
    __weak UIView *sView=supportView;
    [supportButton handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
       // if(!me.isSupported){
            if([self.delegate respondsToSelector:@selector(supportClickedWihtIndexPath:)]){
                
              
                [[SgrGCD sharedInstance] enqueueForegroundWithDelay:0.5 block:^{
                    IfengLabel *backgroundView = (IfengLabel *)[me.contentView viewWithTag:10];
                    UIImageView *supportImageView = (UIImageView *)[backgroundView viewWithTag:10002];
                    
                    [me addOneAnimation:CGPointMake(supportImageView.right, supportImageView.top)
                                       :sView];

                }];
                
               
                NSMutableDictionary *dic=[NSMutableDictionary dictionary];
                [dic sgrSetObject:me.indexPath forKey:@"indexPath"];
                [dic sgrSetObject:me.dataDic forKey:@"sourceDic"];
                
                me.isSupported=YES;
                [me.delegate performSelector:@selector(supportClickedWihtIndexPath:)
                                    withObject:dic];
                           }
      //  }
    }];
    
}

- (void)addOneAnimation:(CGPoint )point :(UIView *)sView{
    UILabel *add=[UILabel new];
    add.font=[UIFont systemFontOfSize:8.f];
    add.textColor=RGB(0xf5, 0x43, 0x43);
    add.text=@"+1";
    CGRect frame=CGRectMake(point.x, point.y, 10.f, 10.f);
    
    add.frame=frame;
    [sView addSubview:add];
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect frame1=add.frame;
                         frame1.origin.y-=11.f;
                         add.frame=frame1;
                         add.alpha=0.f;
                         add.font=[UIFont systemFontOfSize:10.f];
                     } completion:^(BOOL finished) {
                         [add removeFromSuperview];
                     }];
}


- (void)initTimeView
{
    IfengLabel *backgroundView = (IfengLabel *)[self.contentView viewWithTag:10];
    UILabel *zoneLabel = (UILabel *)[backgroundView viewWithTag:1001];
    
    NSString *commentTime = nil;
    if(dataDic && [dataDic isKindOfClass:[NSDictionary class]])
    {
        NSString *timeStr = [dataDic sgrGetStringForKey:@"comment_date"];
        if(!timeStr || [timeStr length] == 0)
            return;
        commentTime = timeStr;
    }
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.backgroundColor = [UIColor clearColor];
    timeLabel.tag  = 104;
    timeLabel.numberOfLines = 1;
    timeLabel.frame = CGRectMake(zoneLabel.frame.origin.x + zoneLabel.frame.size.width + 20, zoneLabel.frame.origin.y, 200, zoneLabel.frame.size.height);
    timeLabel.text = commentTime;
    timeLabel.font = [UIFont systemFontOfSize:14];
    timeLabel.textColor = RGB(0xa6, 0xa6, 0xa6);
    [backgroundView addSubview:timeLabel];
}


- (void)initCommentContentsLabel  //表示用户评论内容的Label
{
    IfengLabel *backgroundView = (IfengLabel *)[self.contentView viewWithTag:10];
    
    NSString *commentStr = nil;
    if(dataDic && [dataDic isKindOfClass:[NSDictionary class]])
    {
        commentStr = [dataDic sgrGetStringForKey:@"comment_contents"];
    }
    commentStr = [commentStr stringByReplacingOccurrencesOfString:@"<br>" withString:@""];
    commentStr = [commentStr stringByReplacingOccurrencesOfString:@"&quot" withString:@""];
    if (!commentStr) {
        commentStr = @"";
    }
    UILabel *zoneLabel = (UILabel *)[self viewWithTag:1001];
    
    PlanningTopicCoreTextLabel *commentLabel = [[PlanningTopicCoreTextLabel alloc] init];
    commentLabel.font=commentFont;
    commentLabel.lineSpace = commentLineSpace;
    commentLabel.textColor=RGB(0x54, 0x54, 0x54);
    commentLabel.backgroundColor = [UIColor clearColor];
    commentLabel.text = commentStr;
    commentLabel.tag = 1002;
    CGSize maxSize = commentMaxSize;
    CGSize size = [[CLGloble sharedInstance] calculateSizeWithFont:[UIFont systemFontOfSize:15.0f]
                                       withText:commentStr
                                    withMaxSize:maxSize
                                  withLineSpace:commentLineSpace
                                withAllowIndent:NO];
    commentLabel.frame = CGRectMake(leftMarginOfComment,zoneLabel.frame.origin.y+zoneLabel.frame.size.height + intervalZoneAndComment, maxSize.width, size.height+20);
    [backgroundView addSubview:commentLabel];
}

- (void)addSeperatorLineView
{
    IfengLabel *backgroundView = (IfengLabel *)[self.contentView viewWithTag:10];

    UIView *line = [UIView new];
    if([self.comeFrom isEqualToString:@"topic"])
        line.frame = CGRectMake(53, 0, GlobleWidth-58-8, 0.5f);
    else
        line.frame = CGRectMake(53, CGRectGetHeight(backgroundView.frame)-0.5, 254, 0.5);
    line.backgroundColor = RGB(0xd7, 0xd7, 0xd7);
    [backgroundView addSubview:line];
    
    [backgroundView addSubview:line];
    [backgroundView bringSubviewToFront:line];
}

-(void)addSufaceView{
    IfengLabel *backgroundView = (IfengLabel *)[self.contentView viewWithTag:10];
    UIView *sufaceView = [[UIView alloc] initWithFrame:backgroundView.frame];
    sufaceView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:sufaceView];
    [self.contentView bringSubviewToFront:sufaceView];
}
#pragma mark -
#pragma mark Calculation Height Methods

- (float)calculationHeight
{
    float height = 0.0;
    height = height + intervalFromTop;
    height = height + zoneHeight;

    NSString *text = [dataDic sgrGetStringForKey:@"comment_contents"];
    if (!text||![text length]) {
        text = @"";
    }
    CGSize commentSize = [[CLGloble sharedInstance] calculateSizeWithFont:commentFont
                                              withText:text
                                           withMaxSize:commentMaxSize
                                         withLineSpace:commentLineSpace
                                       withAllowIndent:NO];
    height = height +commentSize.height+ intervalZoneAndComment+15;
    return height;
}

#pragma mark -
#pragma IfengLabel Delegate Methods

- (void)ifengLabelDidSingleClickAtIndex:(NSNumber *)index
                               withData:(NSDictionary *)dic
                              withLevel:(NSNumber *)level
                     withLocateInWindow:(CGPoint)locateInWindow
                       withLocateInCell:(CGPoint)locateInCell
                         withSizeOfCell:(CGSize)sizeOfCell
                        withView:(UIView *)view
{
    if(!self.isSupportClick)
        return;
    if(self.delegate && [self.delegate respondsToSelector:@selector(addReplayAtIndexPath:withLocateInWindow:withLocateInCell:withSizeOfCell:withSourceDic:atParentsArrayIndex:withLevel:withView:)])
        [(CTCommentTable *)self.delegate addReplayAtIndexPath:indexPath withLocateInWindow:locateInWindow withLocateInCell:locateInCell withSizeOfCell:sizeOfCell withSourceDic:dic atParentsArrayIndex:[index integerValue] withLevel:level withView:view];
}


#pragma mark -
#pragma mark Support
- (void)supportComment
{
    IfengLabel *backgroundView = (IfengLabel *)[self viewWithTag:10];
    UIView *supportView = (UIView *)[backgroundView viewWithTag:10001];
    UIImageView *supportImageView = (UIImageView *)[supportView viewWithTag:10002];
    UILabel *supportCountLabel = (UILabel *)[supportView viewWithTag:10003];
    
    
    supportImageView.hidden=YES;
   CGRect frame= [supportView convertRect:supportImageView.frame toView:[[CLGloble sharedInstance] getMainWindow]];
    UIView *animationView = [[UIView alloc]initWithFrame:frame];
    animationView.backgroundColor = [UIColor clearColor];
    
    [[[CLGloble sharedInstance] getMainWindow] addSubview:animationView];
    
    [UIView animateWithDuration:0.4
                     animations:^{
                         
                         CGRect frame = animationView.frame;
                         frame.origin.x-= 8;
                         frame.origin.y -= 24;
                         frame.size.width+=12;
                         frame.size.height+=12;
                         animationView.frame=frame;

                     }
                     completion:^(BOOL finished){
                         
                         CALayer *layer = [CALayer layer];
                         layer.frame = animationView.bounds;
                         layer.contentsGravity = kCAGravityResizeAspect;
                         layer.contents = (id)[UIImage imageNamed:@"comment_replay_supported.png"].CGImage;
                         
                         
                         [[animationView layer] addSublayer:layer];
                         
                         [[SgrGCD sharedInstance] enqueueForeground:^{

                                 [CATransaction begin];
                                 
                                 [CATransaction setCompletionBlock:^{
                                     [CATransaction begin];
                                     [CATransaction setAnimationDuration:1.];
                                     [CATransaction setCompletionBlock:^{
                                         supportImageView.hidden=NO;
                                         [animationView removeFromSuperview];
                                         }];
                                     layer.transform = CATransform3DMakeRotation((M_PI / 180.0) * 360.0f, 0.0f, 1.0f,0.0f);

                                     [CATransaction commit];
                                 }];

                                 [CATransaction setAnimationDuration:1.];
                                 layer.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 1.0f,0.0f);
                                 
                                 [CATransaction commit];

                                 }];
                     }];

    [supportImageView setImage:[UIImage imageNamed:@"comment_replay_supported.png"]];
    
    
    NSString *supportedNumStr = [NSString stringWithFormat:@"%d",[supportCountLabel.text intValue]+1];
    [supportCountLabel setText:supportedNumStr];
    
    CGSize supportStrSize = [supportedNumStr sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(50, 12)];
//    supportImageView.frame = CGRectMake(supportView.width-supportImageView.width, 0, supportImageView.width, supportImageView.height);
    supportCountLabel.frame = CGRectMake(supportView.width-supportImageView.width-supportStrSize.width, 2, supportStrSize.width, 12);
    self.isSupported=YES;
}

- (void)nameTapResponse:(id)sender
{
    if(delegate && [delegate respondsToSelector:@selector(nameTapWithData:withIndexPath:)])
    {
        [delegate performSelector:@selector(nameTapWithData:withIndexPath:)
                       withObject:self.dataDic
                       withObject:self.indexPath];
    }
}



@end
